package com.example.base;

import com.example.util.CommonUtils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CommonUtils.printThreadLog("main start");

        ExecutorService executor = Executors.newFixedThreadPool(4);

        CompletableFuture<String> newsFuture = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读文件，开始");
            String content = CommonUtils.readFile("news.txt");
            CommonUtils.printThreadLog("读文件，结束");
            return content;
        }, executor);

        CommonUtils.printThreadLog("main continue");
        // 阻塞，等待 newsFuture 执行完成
        String content = newsFuture.get();
        System.out.println(content);

        executor.shutdown();

        CommonUtils.printThreadLog("main end");
    }
}
